const express = require("express");
const db = require("./db");
const app = express();
const port = 3000;
//配置body-parser
// 只要加上这个配置，则在req请求对象上会多出来一个属性：body
// 因此可以直接通过req.body来获取表单post请求体数据
const bodyParser=require("body-parser");
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
//配置跨域以及请求头
app.use((req, res, next) => {
    //设置请求头
    res.set({
      'Access-Control-Allow-Credentials': true,
      'Access-Control-Max-Age': 1728000,
      'Access-Control-Allow-Origin': req.headers.origin || '*',
      'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type',
      'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
      'Content-Type': 'application/json; charset=utf-8'
    })
    req.method === 'OPTIONS' ? res.status(204).end() : next()
  })
 
app.get("/",(req,res)=>{
    res.json({
        code:200,
        msg:"接口成功"
    })
})
//查询接口
app.get("/search",(req,res)=>{
    // console.log(req.query);
    let data = req.query;
    let sql = "";
    // console.log(Object.keys(data));
    if(Object.keys(data).length){
        sql = `select * from user where name= "${data.name}"`;
    }else{
        sql = "select * from user";
    }  
    db(sql,(err,results)=>{
        if(err){ throw err };
        res.send({
            code:200,
            msg:"查询成功",
            data:results
        })
    })
   
})
//登录接口
app.all("/login",(req,res)=>{
    let data = "";
    if(Object.keys(req.query).length){
        data = req.query;
    }else{
        data = req.body;
    }
    // let data = req.query;
    let  sql = `select * from user where name= "${data.name}" and password = "${data.password}" `;
    db(sql,(err,results)=>{
        if(err){ throw err};
        console.log(results);
        if(Object.keys(results).length){
            res.send({
                code:200,
                msg:"登陆成功",
                data:results
            })
        }else{
            let sql = `select * from user where name = "${data.name}"`;
            db(sql,(err,results)=>{
                if(err){throw err};
                if(Object.keys(results).length){
                    res.json({
                        code:1002,
                        msg:"用户或密码不正确"
                    })
                }else{
                    res.json({
                        code:1001,
                        msg:"此用户不存在"
                    })
                }
            })
        }

    })

})
//注册接口
app.post("/register",(req,res)=>{
    
    // console.log(req.body);
    let data = req.body;
    let  sql = `select * from user where name= "${data.name}"`;
    db(sql,(err,results)=>{
        if(err){ throw err };
        if(Object.keys(results).length){
            res.send({
                code:101,
                msg:"用户已存在，请直接登录"
            })
        }else{
            regsiter(data,res)
        }
    })

})

//注册方法
function regsiter(data,res){
    let sql =  `INSERT INTO user (id, name, password) VALUES (NULL, "${data.name}","${data.password}")`;
    db(sql,(err,results)=>{
        if(err){ throw err };
        res.send({
            code:200,
            msg:"注册成功",
            data:results
        })
    })
}

app.listen(port,()=>{
    console.log(3000);
})